// background.js (或你的主脚本文件)

// 函数：创建右键菜单
function createContextMenu() {
  chrome.contextMenus.create({
    id: "sendToLocalhost",
    title: "发送到本地接口",
    contexts: ["selection"]
  });
}

// 监听右键菜单点击事件
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  if (info.menuItemId === "sendToLocalhost" && info.selectionText) {
    const selectionText = info.selectionText;
    const sourceUrl = tab.url;

    let pageTitle = ""; // 默认为空

    // 使用 chrome.scripting.executeScript 直接在页面中执行脚本获取标题
    try {
      const results = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: () => document.title
      });
      
      if (results && results[0] && results[0].result) {
        pageTitle = results[0].result;
        console.log("获取到页面标题:", pageTitle);
      }
    } catch (e) {
      console.error("无法获取页面标题:", e);
      // 如果无法获取，pageTitle 会保持为空字符串
    }

    // 格式化当前时间为YYYY-MM-DD HH:MM:SS
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    const remark = ""; // 备注可以留空或让用户输入，这里暂时留空

    const data = {
      content: selectionText,
      sourceUrl: sourceUrl,
      pageTitle: pageTitle, // 添加网站标题
      copyTime: formattedTime, // 使用格式化后的时间
      remark: remark
    };

    console.log("即将发送的数据:", data); // 打印即将发送的数据，以便调试

    try {
      // 发送POST请求到本地接口
      const response = await fetch("http://localhost:8081/jeecg-boot/deepseek/steam/add", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      });

      if (response.ok) {
        try {
          const responseData = await response.json();
          console.log("数据发送成功:", responseData);
          chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icon48.svg',
            title: '发送成功',
            message: '内容已成功发送到本地接口。'
          });
        } catch (e) {
          console.error("解析成功响应的JSON时出错:", e);
          let errorDetails = "服务器响应不是有效的JSON格式。";
          try {
            const textResponse = await response.text();
            errorDetails += ` 服务端响应内容: ${textResponse.substring(0, 100)}...`;
          } catch (textError) {
            console.error("读取响应文本失败:", textError);
          }
          chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icon48.svg',
            title: '发送成功但响应异常',
            message: errorDetails
          });
        }
      } else {
        const errorText = await response.text();
        console.error("数据发送失败:", response.status, response.statusText, errorText);
        chrome.notifications.create({
          type: 'basic',
          iconUrl: 'icon48.svg',
          title: '发送失败',
          message: `无法连接到服务器或请求失败。错误码: ${response.status}. 详情: ${errorText}`
        });
      }
    } catch (error) {
      console.error("发送请求时发生网络错误:", error);
      let message = `发送请求时发生网络错误: ${error.message}`;
      chrome.notifications.create({
        type: 'basic',
        iconUrl: 'icon48.svg',
        title: '发送错误',
        message: message
      });
    }
  }
});

// 插件安装或更新时创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
  createContextMenu();
});

// 浏览器启动时创建右键菜单（以防万一）
chrome.runtime.onStartup.addListener(() => {
  createContextMenu();
});